﻿using AutoMapper;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Write.API.Application.Commands.DepartmentCommand;
using MediatR;

namespace D.Medicalcare.Write.API.Application.Handlers.DepartmentHarder
{
    public class AddDepartmentHarder : IRequestHandler<AddDepartmentCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Department> repository;
        private readonly IMapper mapper;
       private readonly ILogger<AddDepartmentHarder> logger;

        public AddDepartmentHarder(IBaseRepository<Department> repository, IMapper mapper, ILogger<AddDepartmentHarder> logger)
        {
            this.repository = repository;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<APIResult<int>> Handle(AddDepartmentCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();
                result.Code = APIEnum.Success;
                result.Msg = "添加成功";
                var xi = mapper.Map<Department>(request);
                var a = repository.AddAsync(xi).Result;
                if (a > 0)
                {
                    result.Code = APIEnum.Success;
                    result.Msg = "添加成功";
                    result.Data = a;

                    logger.LogInformation("添加科室成功");
                }
                else
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "添加失败";
                    result.Data = a;
                    logger.LogError("添加科室成功");

                }

                return await Task.FromResult(result);

            }
            catch (Exception ex)
            {
                logger.LogError("新增科室异常" + ex.Message);
                throw;
            }



        }
    }
}
